package gr.unipi.cinema;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;

public class Reserve {
	
	public static ReserveData[] getReservations(int showId) {
		ReserveData[] res = null;
		Connection connection = SqlConnection.getConnection();
		if (connection == null) {
			System.out.println("Cloud not connect to db");
			return res;
		}
		
		Statement st = null;
		ResultSet resultSet = null;
		
		try {
			st = connection.createStatement();
			
			String sql =
					"SELECT ROWID, COLID " +
					"FROM CRESERVSEATS CS " +
					"JOIN CRESERVATIONS CR " +
					"ON CS.RESERVID = CR.ID " +
					"WHERE CR.SHOWID = " + showId;
			
			System.out.println("Executing query: " + sql);
			
			resultSet = st.executeQuery(sql);
			
			ArrayList<ReserveData> thList = new ArrayList<>(5);
			ReserveData entry = null;
			
			while (resultSet.next()) {
				entry = new ReserveData(resultSet.getInt("ROWID"),
										resultSet.getInt("COLID"));

				thList.add(entry);
			}
			
			res = thList.toArray(new ReserveData[0]);
			
		} catch (SQLException e) {
			e.printStackTrace();
		}
		finally {
			
			if (resultSet != null) {
				try {
					resultSet.close();
				} catch (SQLException e1) {
					e1.printStackTrace();
				}
				resultSet = null;
			}
			
			if (st != null) {
				try {
					st.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
				st = null;
			}
			try {
				connection.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			connection = null;
		}
		
		return res;
	}
}
